package com.lht.admin.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lht.admin.conf.AliyunOssConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;

/**
 * <p>
 *
 * @author cs12110 create at 2020-02-02 23:56
 * <p>
 * @since 1.0.0
 */
@Slf4j
@Component
public class AliyunOssFileUtil {

    @Resource
    private AliyunOssConf aliyunOssConf;


    public String uploadFile(File file, String fileName) {
        try {
            OSS ossClient = new OSSClientBuilder().build(aliyunOssConf.getEndpoint(), aliyunOssConf.getId(), aliyunOssConf.getSecret());
            ossClient.putObject(aliyunOssConf.getBucket(), fileName, file);
            ossClient.shutdown();
        } catch (Exception e) {
            log.error("Function[uploadFile] by File", e);
        }

        return aliyunOssConf.getVisitSite() + "/" + fileName;
    }


    public String uploadFile(InputStream in, String fileName) {
        try {
            OSS ossClient = new OSSClientBuilder().build(aliyunOssConf.getEndpoint(), aliyunOssConf.getId(), aliyunOssConf.getSecret());
            ossClient.putObject(aliyunOssConf.getBucket(), fileName, in);
            ossClient.shutdown();
        } catch (Exception e) {
            log.error("Function[uploadFile] by In", e);
        }

        return aliyunOssConf.getVisitSite() + "/" + fileName;
    }

}
